package com.whh.tq.common;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class HttpHelper {
	public final static String DEFALUT_ENCODING = "UTF-8";
	public static DefaultHttpClient httpClient ;
//	private static List<BasicHeader> headers ;

	/**
	 * 获取httpClient
	 */
	public static DefaultHttpClient getHttpClient(){
		//获取线程安全的httpClient，从老外的网站上找到的，不知道对否
		if (httpClient == null) {
			httpClient = new DefaultHttpClient();
			ClientConnectionManager connMgr = httpClient.getConnectionManager();
			HttpParams params = httpClient.getParams();
			ThreadSafeClientConnManager safeConnMgr = new ThreadSafeClientConnManager(params, connMgr.getSchemeRegistry());
			httpClient = new DefaultHttpClient(safeConnMgr, params);
		}
		return httpClient;
	}
	
	/**
	 * 获取表单请求的header
	 */
//	public static List<BasicHeader> getFormHeaders() {
//		if(null==headers){
//			headers = new ArrayList<BasicHeader>();
//			headers.add(new BasicHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"));
//			headers.add(new BasicHeader("Host", "dynamic.12306.cn"));
//			headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"));
//			headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
//			headers.add(new BasicHeader("Accept-Language", "zh-cn,zh;q=0.5"));
//			headers.add(new BasicHeader("Accept-Encoding	", "gzip, deflate"));
//			headers.add(new BasicHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"));
//			headers.add(new BasicHeader("Connection", "keep-alive"));
//		}
//		return headers;
//	}
	
	/**
	 * 获取图片,由于需要获取cookie，所以使用httpClient获取
	 * @param url
	 * @return
	 */
	public static Drawable getDrawable(String url) {
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = HttpHelper.getHttpClient().execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.i(AndroidHelper.LOG_TAG,"getDrawable statusCode : "+statusCode);
			if(statusCode != HttpStatus.SC_OK){
				return null;
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			Bitmap bitmap = BitmapFactory.decodeStream(httpEntity.getContent());
			Drawable drawable = new BitmapDrawable(bitmap);
			return drawable;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 提交表单并获取html代码
	 * @param url
	 * @param nvps
	 * @return
	 */
	public static String getHtml(String url, List<NameValuePair> nvps) {
		try {
			List<Cookie> cookies = HttpHelper.getHttpClient().getCookieStore().getCookies();
			HttpPost httpPost = new HttpPost(url);
			// 二次请求需要带上cookie中的session，这样服务端会认为是同一次链接校验验证码
			for (Cookie cookie : cookies) {
				if(cookie.getName().equalsIgnoreCase("JSESSIONID"))
					httpPost.addHeader(cookie.getName(), cookie.getValue());
			}
			
			// 设置请求头参数，设置后在gprs网络下会出现读取内容时contentLength不对，读取到乱七八糟的东西，不知道为什么，在wifi下正常，
			//List<BasicHeader> headers = HttpHelper.getFormHeaders();
			//for (BasicHeader header : headers) {
			//	httpPost.addHeader(header);
			//}
			
			// 抓取所请求html内容
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,DEFALUT_ENCODING));
			HttpResponse httpResponse = HttpHelper.getHttpClient().execute(httpPost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.i(AndroidHelper.LOG_TAG,"getHtml statusCode : "+statusCode);
			if(statusCode != HttpStatus.SC_OK){
				return null;
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			Log.i(AndroidHelper.LOG_TAG,"getHtml contentLength : "+httpEntity.getContentLength());
			String res = EntityUtils.toString(httpEntity, DEFALUT_ENCODING);
			Log.i(AndroidHelper.LOG_TAG,"getHtml content : "+res);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getHtml(String url,String referer){
		try {
			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader(new BasicHeader("Referer", referer));
			HttpResponse httpResponse = HttpHelper.getHttpClient().execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.i(AndroidHelper.LOG_TAG,"getHtml statusCode : "+statusCode);
			if(statusCode != HttpStatus.SC_OK){
				return null;
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			Log.i(AndroidHelper.LOG_TAG,"getHtml contentLength : "+httpEntity.getContentLength());
			String res = EntityUtils.toString(httpEntity, DEFALUT_ENCODING);
			Log.i(AndroidHelper.LOG_TAG,"getHtml content : "+res);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}		
	}
}
